package com.xgy.userauthsystem.exception;

import com.xgy.userauthsystem.dto.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 * 统一处理系统中的各种异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数验证异常
     * @param ex 验证异常
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<Map<String, String>>> handleValidationExceptions(
            MethodArgumentNotValidException ex) {
        logger.warn("参数验证失败: {}", ex.getMessage());

        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        ApiResponse<Map<String, String>> response = ApiResponse.error("参数验证失败", "VALIDATION_ERROR");
        response.setData(errors);
        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理用户名已存在异常
     * @param ex 用户名已存在异常
     * @return 错误响应
     */
    @ExceptionHandler(UsernameAlreadyExistsException.class)
    public ResponseEntity<ApiResponse<String>> handleUsernameAlreadyExists(
            UsernameAlreadyExistsException ex) {
        logger.warn("用户名已存在异常: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.CONFLICT).body(
                ApiResponse.error(ex.getMessage(), "USERNAME_EXISTS")
        );
    }

    /**
     * 处理邮箱已存在异常
     * @param ex 邮箱已存在异常
     * @return 错误响应
     */
    @ExceptionHandler(EmailAlreadyExistsException.class)
    public ResponseEntity<ApiResponse<String>> handleEmailAlreadyExists(
            EmailAlreadyExistsException ex) {
        logger.warn("邮箱已存在异常: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.CONFLICT).body(
                ApiResponse.error(ex.getMessage(), "EMAIL_EXISTS")
        );
    }

    /**
     * 处理密码无效异常
     * @param ex 密码无效异常
     * @return 错误响应
     */
    @ExceptionHandler(InvalidPasswordException.class)
    public ResponseEntity<ApiResponse<String>> handleInvalidPassword(
            InvalidPasswordException ex) {
        logger.warn("密码无效异常: {}", ex.getMessage());
        return ResponseEntity.badRequest().body(
                ApiResponse.error(ex.getMessage(), "INVALID_PASSWORD")
        );
    }

    /**
     * 处理登录无效异常
     * @param ex 登录无效异常
     * @return 错误响应
     */
    @ExceptionHandler(InvalidLoginException.class)
    public ResponseEntity<ApiResponse<String>> handleInvalidLogin(
            InvalidLoginException ex) {
        logger.warn("登录无效异常: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(
                ApiResponse.error(ex.getMessage(), "INVALID_CREDENTIALS")
        );
    }

    /**
     * 处理验证码无效异常
     * @param ex 验证码无效异常
     * @return 错误响应
     */
    @ExceptionHandler(InvalidCaptchaException.class)
    public ResponseEntity<ApiResponse<String>> handleInvalidCaptcha(
            InvalidCaptchaException ex) {
        logger.warn("验证码无效异常: {}", ex.getMessage());
        return ResponseEntity.badRequest().body(
                ApiResponse.error(ex.getMessage(), "INVALID_CAPTCHA")
        );
    }

    /**
     * 处理邮箱不存在异常
     * @param ex 邮箱不存在异常
     * @return 错误响应
     */
    @ExceptionHandler(EmailNotFoundException.class)
    public ResponseEntity<ApiResponse<String>> handleEmailNotFound(
            EmailNotFoundException ex) {
        logger.warn("邮箱不存在异常: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
                ApiResponse.error(ex.getMessage(), "EMAIL_NOT_FOUND")
        );
    }

    /**
     * 处理邮箱验证码过期异常
     * @param ex 邮箱验证码过期异常
     * @return 错误响应
     */
    @ExceptionHandler(EmailCodeExpiredException.class)
    public ResponseEntity<ApiResponse<String>> handleEmailCodeExpired(
            EmailCodeExpiredException ex) {
        logger.warn("邮箱验证码过期异常: {}", ex.getMessage());
        return ResponseEntity.badRequest().body(
                ApiResponse.error(ex.getMessage(), "EMAIL_CODE_EXPIRED")
        );
    }

    /**
     * 处理邮箱验证码错误异常
     * @param ex 邮箱验证码错误异常
     * @return 错误响应
     */
    @ExceptionHandler(EmailCodeIncorrectException.class)
    public ResponseEntity<ApiResponse<String>> handleEmailCodeIncorrect(
            EmailCodeIncorrectException ex) {
        logger.warn("邮箱验证码错误异常: {}", ex.getMessage());
        return ResponseEntity.badRequest().body(
                ApiResponse.error(ex.getMessage(), "EMAIL_CODE_INCORRECT")
        );
    }

    /**
     * 处理其他未预期的异常
     * @param ex 通用异常
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<String>> handleGenericException(Exception ex) {
        logger.error("未预期的系统异常", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                ApiResponse.error("系统内部错误，请联系管理员", "INTERNAL_ERROR")
        );
    }
}